﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using log4net;

namespace RemotePrintTimer
{
    class UploadPdf
    {
        //private static readonly ILog log = LogManager.GetLogger(typeof(UploadPdf));
        //public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");//这里的 loginfo 和 log4net.config 里的名字要一样
        //public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");//这里的 logerror 和 log4net.config 里的名字要一样

 
         private String productCode;
         private int fileCount = 0;
        //OutputMsg outMsg = new OutputMsg();
         Action<String> callback = null;

        public void uploadPdf(Action<String> callback)
        {
            this.callback = callback;
            // LogHelper.WriteLog("转换pdf开始！");
            //if (Directory.Exists(@"c:\destination_directory"))
            //{
            //    Directory.Delete(@"c:\destination_directory", true);
            //}
            // LogHelper.WriteLog("查找目录完成！");
            //PdfHelper ph = new PdfHelper();
            //Dictionary<String, String> map = ph.pdfFileSearchAndCopy(GValues.searchPath, @"c:\destination_directory", woMap);
            List<string> pdfFiles = GetPDFFiles(GValues.pdfPath);
            // 确保目标目录存在
            // LogHelper.WriteLog("文件开始上传！" + JsonConvert.SerializeObject(pdfFiles));
            LogHelper.WriteLog("文件开始上传！" + JsonConvert.SerializeObject(pdfFiles));
            //foreach (string file in pdfFiles)
            //{
                        
            //}
            if (pdfFiles.Count > 0)
            {
                GValues.uploadComplete = false;
                GValues.uploadTimeCount = 20000;
                productCode = Path.GetFileNameWithoutExtension(pdfFiles[0]);
                string filename = Path.GetFileName(pdfFiles[0]);
                FileInfo fileInfo = new FileInfo(pdfFiles[0]);

                if (fileInfo.Exists)
                {
                    DateTime creationTime = fileInfo.CreationTime;
                    // 获取当前时间
                    DateTime now = DateTime.Now;

                    // 比较文件产生时间与当前时间
                    TimeSpan difference = now - creationTime;
                    if (difference.Seconds > 2)
                    {
                        try
                        {

                            LogHelper.WriteLog("开始调Http！Code " + productCode);
                            if (productCode.IndexOf("-process-") != -1)
                            {
                                int index = productCode.IndexOf("-process-");
                                String code = productCode.Substring(0, index);
                                String afterWord = productCode.Substring(index + "-process-".Length);
                                List<String> words = afterWord.Split('-').ToList();                               
                                this.autoUploadProcessPdf(pdfFiles[0],code,words[0],words[1]);
                            }
                            else if (productCode.IndexOf("-material") != -1) {
                                int index = productCode.IndexOf("-material");
                                String code = productCode.Substring(0, index);
                                this.BaigeUploadMaterial(pdfFiles[0],code);
                            }
                            else if (productCode.IndexOf("-other") != -1)
                            {
                                int index = productCode.IndexOf("-other");
                                String code = productCode.Substring(0, index);
                                this.BaigeUploadOther(pdfFiles[0],code);
                            }
                            else if (filename.IndexOf(".png") != -1)
                            {
                                String code = productCode;
                                this.BaigeUploadPNG(pdfFiles[0], code);
                            }                             
                            else
                            {
                                this.autoUploadPdf(pdfFiles[0]);    
                            }
                        
                        }
                        catch (Exception e)
                        {
                           LogHelper.WriteLog("开始传报错！Code " + productCode,null );
                           this.movePDFFile(pdfFiles[0], productCode);
                        }

                    }
                }
            }
            else
            {
                GValues.uploadTimeCount = 120000;
            }

            // LogHelper.WriteLog("文件上传结束！");
            //if (fileCount == 0)
            //{
            //    GValues.uploadComplete = true;
            //}

        }

        private void movePDFFile(string file,string filename)
        {
            try
            {
                GValues.uploadComplete = true;
                // 确保目标路径存在
                var destinationDirectory = Path.GetDirectoryName(GValues.pdfPath + "\\error\\");
                if (!Directory.Exists(destinationDirectory))
                {
                    Directory.CreateDirectory(destinationDirectory);
                }
                var destinationFile = (GValues.pdfPath + "\\error\\" + filename + ".pdf");
                // 删除目标文件，如果它存在
                if (File.Exists(destinationFile))
                {
                    File.Delete(destinationFile);
                }
                // 移动文件
                File.Move(file, (GValues.pdfPath + "\\error\\" + filename + ".pdf"));
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("移动文件报错！", e);
            }
        }
        private List<string> GetPDFFiles(string path)
        {
            DirectoryInfo directory = new DirectoryInfo(path);
            FileInfo[] files = directory.GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
            FileInfo[] pngFiles = directory.GetFiles("*.png", SearchOption.TopDirectoryOnly);
            List<string> pdfFiles = new List<string>();

            foreach (FileInfo file in files)
            {
                pdfFiles.Add(file.FullName);
            }
            foreach (FileInfo file in pngFiles)
            {
                pdfFiles.Add(file.FullName);
            }

            return pdfFiles;
        }
        public void autoUploadProcessPdf(String filename,String code,String processId,String handleId)
        {
            try
            {
                Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant + "/plot", GValues.tenant, GValues.token).UploadFileAsync(filename, new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r1.AckStr());
                        BasProduct basProduct = new BasProduct();
                        basProduct.attachment = cc.message;
                        basProduct.code = code ;
                        basProduct.cadHandleId = handleId;
                        basProduct.processId = processId;
                        saveProductProcessAttachemt(basProduct, filename);
                        //this. LogHelper.WriteLog("上传产品Code " + this.productCode); 
                    }
                    else
                    {
                        LogHelper.WriteLog("上传图纸报错！" + r1.Code + " " + " " + responCode + " " + r1.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传图纸报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
        }
        public void BaigeUploadMaterial(String filename,String code)
        {
            try
            {
                Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant + "/eng", GValues.tenant, GValues.token).UploadFileAsync(filename, new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r1.AckStr());
                        BasMaterial basMaterial = new BasMaterial();
                        basMaterial.attachment = cc.message;
                        basMaterial.code = code;
                        saveMaterialAttachemt(basMaterial, filename);
                        //this. LogHelper.WriteLog("上传产品Code " + this.productCode); 
                    }
                    else
                    {
                        LogHelper.WriteLog("上传图纸报错！" + r1.Code + " " + " " + responCode + " " + r1.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传图纸报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
        }
        public void BaigeUploadOther(String filename,String code)
        {
            try
            {
                Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant + "/eng", GValues.tenant, GValues.token).UploadFileAsync(filename, new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r1.AckStr());
                        BasProduct basProduct = new BasProduct();
                        basProduct.attachment = cc.message;
                        basProduct.code = code ;
                        saveProductOtherAttachemt(basProduct, filename);
                        //this. LogHelper.WriteLog("上传产品Code " + this.productCode); 
                    }
                    else
                    {
                        LogHelper.WriteLog("上传图纸报错！" + r1.Code + " " + " " + responCode + " " + r1.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传图纸报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
        }

        public void BaigeUploadPNG(String filename, String code)
        {
            try
            {
                Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant + "/eng", GValues.tenant, GValues.token).UploadFileAsync(filename, new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r1.AckStr());
                        BasProduct basProduct = new BasProduct();
                        basProduct.thumbnailAttachment = cc.message;
                        basProduct.code = code;
                        saveProductOtherAttachemt(basProduct, filename);
                        //this. LogHelper.WriteLog("上传产品Code " + this.productCode); 
                    }
                    else
                    {
                        LogHelper.WriteLog("上传图纸报错！" + r1.Code + " " + " " + responCode + " " + r1.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传图纸报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
        }
        public void autoUploadPdf(String filename)
        {
            try
            {
                Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant + "/plot", GValues.tenant, GValues.token).UploadFileAsync(filename, new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r1.AckStr());
                        BasProduct basProduct = new BasProduct();
                        basProduct.attachment = cc.message;
                        basProduct.code = this.productCode;;
                        saveProductAttachemt(basProduct,filename);
                        //this. LogHelper.WriteLog("上传产品Code " + this.productCode); 
                    }
                    else
                    {
                        LogHelper.WriteLog("上传图纸报错！" + r1.Code + " " + " " + responCode + " " + r1.Error,null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传图纸报错！" + e.Message,null);
                this.movePDFFile(filename, productCode);
            }
        }
        public void saveProductProcessAttachemt(BasProduct basProduct, String filename)
        {
            try
            {

                JObject jsonObject = new JObject();
                jsonObject["productCode"] = basProduct.code;
                jsonObject["processId"] = basProduct.processId;
                jsonObject["handleId"] = basProduct.cadHandleId;
                jsonObject["attachment"] = basProduct.attachment;

                string postData = JsonConvert.SerializeObject(jsonObject);
                Http.CreateHttpClient(GValues.domainLink + "mrp/mrpProcessBom/cad-add-attachment", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r.AckStr());
                        if (cc.success)
                        {
                            //this. LogHelper.WriteLog("上传图纸成功！" + filename);
                            Task.Delay(200);
                            File.Delete(filename);
                            LogHelper.WriteLog("上传图纸成功！" + filename);
                            GValues.uploadComplete = true;
                            callback(productCode);
                        }
                        else
                        {
                            LogHelper.WriteLog(cc.message + "/" + filename, null);
                            this.movePDFFile(filename, productCode);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("上传附件数据失败！" + r.Code + " " + " " + responCode + " " + r.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (IOException e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }

        }

        public void saveMaterialAttachemt(BasMaterial basMaterial, String filename)
        {
            try
            {
                string postData = JsonConvert.SerializeObject(basMaterial);
                Http.CreateHttpClient(GValues.domainLink + "bas/basMaterial/cad-add-attachment", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r.AckStr());
                        if (cc.success)
                        {
                            //this. LogHelper.WriteLog("上传图纸成功！" + filename);
                            Task.Delay(200);
                            File.Delete(filename);
                            LogHelper.WriteLog("上传图纸成功！" + filename);
                            GValues.uploadComplete = true;
                            callback(productCode);
                        }
                        else
                        {
                            LogHelper.WriteLog(cc.message + "/" + filename, null);
                            this.movePDFFile(filename, productCode);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("上传附件数据失败！" + r.Code + " " + " " + responCode + " " + r.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (IOException e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }

        }  

        public void saveProductOtherAttachemt(BasProduct basProduct, String filename)
        {
            try
            {
                string postData = JsonConvert.SerializeObject(basProduct);
                Http.CreateHttpClient(GValues.domainLink + "bas/basProduct/cad-add-other", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r.AckStr());
                        if (cc.success)
                        {
                            //this. LogHelper.WriteLog("上传图纸成功！" + filename);
                            Task.Delay(200);
                            try
                            {
                                File.Delete(filename);
                            }
                            catch (IOException ex)
                            {
                                LogHelper.WriteLog("删除文件失败！" + filename + " " + ex.Message);
                            }
                          
                            LogHelper.WriteLog("上传图纸成功！" + filename);
                            GValues.uploadComplete = true;
                            callback(productCode);
                        }
                        else
                        {
                            LogHelper.WriteLog(cc.message + "/" + filename, null);
                            this.movePDFFile(filename, productCode);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("上传附件数据失败！" + r.Code + " " + " " + responCode + " " + r.Error, null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (IOException e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }

        }    
        public void saveProductAttachemt(BasProduct basProduct,String filename)
        {
            try
            {
                string postData = JsonConvert.SerializeObject(basProduct);
                Http.CreateHttpClient(GValues.domainLink + "bas/basProduct/cad-edit", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r.AckStr());
                        if (cc.success)
                        {
                            //this. LogHelper.WriteLog("上传图纸成功！" + filename);
                            Task.Delay(200);
                            File.Delete(filename);
                            LogHelper.WriteLog("上传图纸成功！" + filename);
                            GValues.uploadComplete = true;
                            callback(productCode);
                        }
                        else
                        {
                            LogHelper.WriteLog(cc.message + "/" + filename, null);
                            this.movePDFFile(filename, productCode);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("上传附件数据失败！" + r.Code + " " + " " + responCode + " " + r.Error,null);
                        this.movePDFFile(filename, productCode);
                    }
                }));
            }
            catch (IOException e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message, null);
                this.movePDFFile(filename, productCode);
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("上传附件报错！" + e.Message,null);
                this.movePDFFile(filename, productCode);
            }

        }    
    }
}
